<?php

namespace app\index\controller;

use app\common\model\Category;
use app\common\model\SentenceComment;
use app\common\validate\SentenceCommentCreateValidate;
use app\common\validate\SentenceCreateValidator;
use think\Request;
use app\common\model\Sentence AS SentenceModel;

class Sentence extends Base
{

    public function create()
    {
        $categories = Category::all();
        return view('', compact('categories'));
    }

    public function store(Request $request)
    {
        $data = $request->only('sentence');
        $this->validator($data, SentenceCreateValidator::class);

        $user = app('auth')->user();
        $sentence = $user->sentences()->save(new SentenceModel([
            'sentence' => $data['sentence']
        ]));

        // 关联标签
        $tags = explode(',', $request->post('tag_ids'));
        $tags && $sentence->tags()->attach($tags);

        $sentence ? $this->success('句子添加成功', '/') : $this->error('句子添加失败');
    }

    public function show($id)
    {
        $sentence = SentenceModel::find($id);
        !$sentence && $this->error('句子不存在', '/');
        return view('', compact('sentence'));
    }

    public function commentHandler(Request $request, $sid)
    {
        $data = $request->only('content');
        $this->validator($data, SentenceCommentCreateValidate::class);

        $sentence = SentenceModel::find($sid);
        !$sentence && $this->error('句子不存在');

        $comment = $sentence->comments()->save(new SentenceComment([
            'user_id' => app('auth')->id(),
            'content' => $data['content'],
        ]));

        !$comment && $this->error('评论失败');
        $this->success('评论成功');
    }

    public function edit($id)
    {
        $sentence = SentenceModel::find($id);
        !$sentence && $this->error('句子不存在');
        $sentence->user_id != app('auth')->id() && $this->error('无权限');

        $categories = Category::all();
        $sentenceTagIds = $sentence->tags()->column('tag_id');

        return view('', compact('sentence', 'categories', 'sentenceTagIds'));
    }

    public function update(Request $request, $id)
    {
        $data = $request->only('sentence');
        $this->validator($data, SentenceCreateValidator::class);

        $sentence = SentenceModel::find($id);
        !$sentence && $this->error('句子不存在');
        $sentence->user_id != app('auth')->id() && $this->error('无权限');

        $sentence->sentence = $data['sentence'];
        $sentence->save();

        // 标签的更新
        $sentence->tags()->detach();
        $tags = explode(',', $request->post('tag_ids'));
        $tags && $sentence->tags()->attach($tags);

        $this->success('句子编辑成功');
    }

    public function destroy($id)
    {
        $sentence = SentenceModel::find($id);
        !$sentence && $this->error('句子不存在');
        $sentence->user_id != app('auth')->id() && $this->error('无权限');
        $sentence->delete();
        $this->success('删除成功', url1('/'));
    }

}
